﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using Oracle.ManagedDataAccess.Client;

namespace ZhCun.CodeBuilder.Builders
{
    class OracleBuiler : BaseBuilder
    {
        public OracleBuiler(string connStr)
            : base(connStr)
        { }
        protected internal override DbConnection CreateConnection()
        {
            return new OracleConnection(base.ConnectString);
        }
        protected override DbCommand CreateDbCommand()
        {
            return new OracleCommand();
        }
        protected override string FormatTableName(string tableName)
        {
            return string.Format("\"{0}\"", tableName);
        }
        protected internal override List<ModelTable> GetTableInfo()
        {
            DataTable tableInfo = null;
            DataTable viewInfo = null;
            using (DbConnection connObj = CreateConnection())
            {
                DataTable table = null;
                DataTable view = null;
                connObj.ConnectionString = ConnectString;
                connObj.Open();

                string findStr = "User ID=";
                int s = ConnectString.IndexOf(findStr, StringComparison.CurrentCultureIgnoreCase);
                int c = ConnectString.IndexOf(";", s, StringComparison.CurrentCultureIgnoreCase);
                string uid = ConnectString.Substring(s + findStr.Length, c - s - findStr.Length);
                //var dt1 = connObj.GetSchema();

                

                table = connObj.GetSchema("Tables");
                table.DefaultView.RowFilter = string.Format("OWNER='{0}'", uid);
                table.DefaultView.Sort = "Table_Name";
                tableInfo = table.DefaultView.ToTable();

                view = connObj.GetSchema("Views");
                view.DefaultView.RowFilter = string.Format("OWNER='{0}'", uid);
                view.DefaultView.Sort = "VIEW_NAME";
                viewInfo = view.DefaultView.ToTable();
            }
            List<ModelTable> list = new List<ModelTable>();
            for (int i = 0; i < tableInfo.Rows.Count; i++)
            {
                ModelTable model = new ModelTable();
                model.IsUse = true;
                model.TableName = tableInfo.Rows[i]["Table_Name"].ToString();
                model.TableRemark = model.TableName;
                model.TableType = TableTypeEnum.Table.ToString();                
                list.Add(model);
            }
            for (int i = 0; i < viewInfo.Rows.Count; i++)
            {
                ModelTable model = new ModelTable();
                model.IsUse = true;
                model.TableName = viewInfo.Rows[i]["VIEW_NAME"].ToString();
                model.TableRemark = model.TableName;
                model.TableType = TableTypeEnum.View.ToString();
                list.Add(model);
            }

            return list;
        }
    }
}